<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import NavBar from '@renderer/components/navBar.vue'
import SelectExportMode from '@renderer/components/selectExportMode.vue'
import useCompute from '@renderer/composables/useCompute'
import useComputeForm from '@renderer/composables/useComputeForm'
import helper from '@renderer/utils/helper'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const pageQuery = route.currentRoute.value.query
const initSubmitForm = () => ({
  cate_name: '',
  print_name: '',
  name: '',
  value: '',
  unit: '',
  main_materials: '',
  labour: '',
  auxiliary_material: '',
  remark: '',
  unit_price: '',
  house_number: '',
})
const submitForm = reactive(initSubmitForm())
const addDataDialog = ref(false)
const selectTemplateDialog = ref(false)
const totalPrice = ref(0)
const changeRow = ref<any[]>([])
const ids = ref([])
const houseNumberOptions = ref<{ value: number; label: string }[]>([])
const total = computed(() => {
  return ((submitForm.unit_price as any) * 1 * ((submitForm.value as any) * 1)).toFixed(2)
})
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  addDataDialog.value = false
  await initPage()
}
const handleAddData = async () => {
  if (changeRow.value.length) {
    await handleSaveTableData(changeRow.value, 26)
    changeRow.value = []
  }
  houseNumberOptions.value = []
  finishedList.value?.forEach((item: FinishedModel) => {
    // 查找houseNumberOptions中是否已经存在该house_number
    if (!houseNumberOptions.value.some((option) => option.value === item.house_number)) {
      if (item.house_number) {
        houseNumberOptions.value.push({
          value: item.house_number,
          label: handleRoomName('', item.house_number),
        })
      }
    }
  })
  addDataDialog.value = true
}
const handleSave = async () => {
  if (!submitForm.name) {
    ElMessage.error('项目代号不能为空')
    return
  }
  if (!submitForm.print_name) {
    ElMessage.error('项目名称不能为空')
    return
  }
  if (!submitForm.house_number && houseNumberOptions.value.length > 1) {
    ElMessage.error('房间层号不能为空')
    return
  }
  if (!submitForm.unit) {
    ElMessage.error('单位不能为空')
    return
  }
  if (!submitForm.unit_price) {
    ElMessage.error('单价不能为空')
    return
  }
  if (!submitForm.value) {
    ElMessage.error('数量不能为空')
    return
  }
  await addBudgetData({
    calculate_id: pageQuery.calculate_id,
    type_name: '成品定制预算',
    cate_name: submitForm.cate_name,
    print_name: submitForm.print_name,
    name: submitForm.name,
    unit: submitForm.unit,
    unit_price: submitForm.unit_price,
    main_materials: submitForm.main_materials,
    labour: submitForm.labour,
    auxiliary_material: submitForm.auxiliary_material,
    remark: finishedList.value![0].remark,
    number: submitForm.value,
    house_number: houseNumberOptions.value.length > 1 ? submitForm.house_number : 1,
  })
  handleClose()
}
const handleExport = async () => {
  selectTemplateDialog.value = true
}
const handleSaveMode = async (event) => {
  handleCloseMode()
  const res = await exportWardrobeTable({
    calculate_id: pageQuery.calculate_id,
    mode: event.mode,
  })
  downLoadFile(res, '成品定制预算明细表.xlsx')
}
const handleCloseMode = () => {
  selectTemplateDialog.value = false
}
const handleBlueCompute = (newVal: FinishedModel, isCompute: boolean = false) => {
  if (isCompute) {
    const childIndex = finishedList.value?.findIndex((item) => item.name == newVal.name)
    if (childIndex != -1) {
      finishedList.value![childIndex!].total_price = (Number(newVal.number) * Number(newVal.unit_price)).toFixed(2) + ''
      const totalIndex = finishedList.value?.findIndex((item) => item.name == '总计')
      if (totalIndex != -1) {
        finishedList.value![totalIndex!].total_price = '0'
        finishedList.value!.forEach((item) => {
          if (item.name != '总计') {
            finishedList.value![totalIndex!].total_price =
              (Number(finishedList.value![totalIndex!].total_price) + Number(item.total_price)).toFixed(2) + ''
          }
        })
      }
    }
  }
  if (!changeRow.value.includes(newVal)) {
    changeRow.value.push(newVal)
  } else {
    changeRow.value = changeRow.value.filter((item) => item !== newVal)
    changeRow.value.push(newVal)
  }
}
const handleSaveData = async () => {
  if (!changeRow.value.length) {
    ElMessage({ type: 'success', message: '保存成功！' })
    return
  }
  await handleSaveTableData(changeRow.value, 26)
  await initPage()
  changeRow.value = []
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const handleDelData = async () => {
  if (changeRow.value.length) {
    ElMessage({ type: 'error', message: '你有未保存的数据，请先保存数据在进行删除此项目。' })
    return
  }
  if (ids.value.length) {
    await delTableData({
      calculate_id: pageQuery.calculate_id,
      ids: ids.value,
      type: 26,
    })
    await initPage()
  } else {
    ElMessage({ type: 'error', message: '请选择要删除的数据' })
  }
}
const initTotalPrice = () => {
  totalPrice.value = 0
  finishedList.value?.forEach((item) => {
    totalPrice.value += (item.total_price as any) * 1
  })
}
const initPage = async () => {
  await getCalculateDetail({ calculate_id: pageQuery.calculate_id })
  if (calculateInfo.value?.check_gather == 2 || !checkRule('预算明细查看权')) {
    ElMessage({ type: 'error', message: '抱歉！您没有此权限' })
    return
  }
  await getFinishedList({
    calculate_id: pageQuery.calculate_id,
    type_name: '成品定制预算',
    client_type: 'GUI',
  })
  await getCalculateTableSet({ type: 4 })
  initTotalPrice()
}
const handleRoomName = (cate_name, house_number) => {
  if ((pageQuery.house_number as any) * 1 > 1) {
    switch (house_number * 1) {
      case 1:
        return '一层' + cate_name
      case 2:
        return '二层' + cate_name
      case 3:
        return '三层' + cate_name
      case 4:
        return '四层' + cate_name
      case 5:
        return '五层' + cate_name
      default:
        return cate_name
    }
  } else {
    return cate_name
  }
}
const currentHandleType = ref('')
const currentFindIndex = ref(-1)
const handleFindReplace = () => {
  currentFindIndex.value = -1
  currentHandleType.value = ''
  window.api.openWindow('findSearch', {
    title: '备注查找与替换',
    currentWindowName: 'basiceQuipment',
    currentPage: 'finished',
  })
}
const handleFind = (content: string) => {
  const includesList = finishedList
    .value!.map((item, index) => (item.print_name && item.print_name.includes(content) ? index : -1))
    .filter((index) => index !== -1)
  if (!includesList.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    return
  }
  if (currentFindIndex.value == -1) {
    currentFindIndex.value = includesList[0]
  } else {
    const currentFind = includesList.findIndex((item) => item === currentFindIndex.value)
    if (currentFind == includesList.length - 1) {
      currentFindIndex.value = includesList[0]
    } else {
      currentFindIndex.value = includesList[currentFind + 1]
    }
  }
  blueInput('name')
}
const handleAllFind = (content: string) => {
  const result = finishedList.value!.filter((item) => item.print_name && item.print_name.includes(content))
  if (!result.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    window.api.sendListArray(JSON.stringify([]))
    return
  }
  window.api.sendListArray(JSON.stringify(result))
}
window.api.acceptSendMsg((handleType, currentPage, content, replaceContent, ids) => {
  if (currentPage == 'finished') {
    switch (handleType) {
      case 'handleFind':
        if (currentHandleType.value == 'handleAllFind') {
          currentFindIndex.value = -1
        }
        handleFind(content)
        break
      case 'handleAllFind':
        currentFindIndex.value = -1
        handleAllFind(content)
        break
      case 'handleReplace':
      case 'handleAllReplace':
        if (ids) {
          let selectIdList = ids.split(',')
          selectIdList.forEach((idItem) => {
            const index = finishedList.value!.findIndex((item) => item.id == Number(idItem))
            handlePlaceRemark(index, content, replaceContent)
          })
        } else {
          if (currentFindIndex.value == -1) {
            ElMessage({ type: 'error', message: '抱歉！未找到匹配的数据！' })
            return
          }
          handlePlaceRemark(currentFindIndex.value, content, replaceContent)
          currentFindIndex.value = -1
        }
        break
    }
    currentHandleType.value = handleType
  }
})
const handlePlaceRemark = (index, content, replaceContent) => {
  finishedList.value![index].print_name = finishedList.value![index].print_name!.replace(content, replaceContent!)
  handleBlueCompute(finishedList.value![index])
}
const blueInput = (type: 'remark' | 'name') => {
  let handleRef = `${type}Input${finishedList.value![currentFindIndex.value].id}`
  const handleRefDom = document.getElementById(handleRef)
  if (handleRefDom) handleRefDom.focus()
}
const { finishedList, getFinishedList, addBudgetData, exportWardrobeTable } = useCompute()
const { downLoadFile, handleSaveTableData, checkRule } = helper()
const {
  getCalculateTableSet,
  calculateSetInfo,
  calculateInfo,
  getCalculateDetail,
  delTableData,
  changeBudgetDataSort,
  updateWardrobeBudgetRemark,
} = useComputeForm()
await initPage()

const handleBlueRemark = async (remark: string) => {
  let replaceRemark = remark.replace(/\n/g, '#')
  await updateWardrobeBudgetRemark({
    calculate_id: pageQuery.calculate_id,
    remark: replaceRemark,
  })
}
interface SpanMethodProps {
  columnIndex: number
  rowIndex: number
}
const objectSpanMethod = ({ rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 8) {
    if (rowIndex % finishedList.value?.length! === 0) {
      return {
        rowspan: finishedList.value?.length,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  } else {
    return
  }
}
const handleSortData = async (event, { e }) => {
  if (event[e.newIndex].name == '总计') {
    ElMessage.error('此次移动仅为方便查看金额，不做排序处理！')
    return
  }
  await changeBudgetDataSort({
    id: event[e.newIndex].id,
    calculate_id: pageQuery.calculate_id,
    type_name: '成品定制预算',
    sort: e.newIndex,
  })
}
const remarkStyle = computed(() => {
  return {
    height: `${remarkHeight.value}px`,
  }
})
const remarkHeight = ref(0)
const observer = new MutationObserver(() => {
  const elements = document.getElementsByClassName('el-table__cell')
  if (elements.length > 0) {
    const firstElement = elements[17]
    remarkHeight.value = firstElement.clientHeight - 50
  }
})

observer.observe(document.body, { childList: true, subtree: true })
</script>

<template>
  <main class="bg-white flex flex-col" style="height: -webkit-fill-available">
    <div class="flex flex-1 justify-center" v-if="calculateInfo?.check_gather == 2 || !checkRule('预算明细查看权')">
      <el-empty
        image="https://cw3.obs.cn-north-4.myhuaweicloud.com/api/uploads/images/b1ed1d14709b890118b4c2b3da9114b351e11b9d.png"
        description="抱歉！您没有此权限" />
    </div>
    <section v-else class="flex flex-col overflow-hidden">
      <div class="px-6 h-[50px] border-b flex items-center bg-white" style="width: -webkit-fill-available">
        <div class="flex gap-3">
          <formButton @click="handleAddData" v-if="checkRule('预算明细修改权')">添加项目</formButton>
          <formButton @click="handleSaveData" v-if="checkRule('预算明细修改权')">保存数据</formButton>
          <formButton @click="handleDelData" v-if="checkRule('预算明细修改权') && ids.length">删除数据</formButton>
          <formButton @click="handleExport">导出</formButton>
          <formButton @click="handleFindReplace" v-if="checkRule('预算明细修改权')">查找替换</formButton>
        </div>
      </div>
      <div class="flex flex-col gap-3 p-6 pt-4 overflow-y-auto flex-1">
        <div class="flex flex-col">
          <div class="text-center font-bold text-2xl text-black mt-3 mb-1">{{ calculateSetInfo?.title }}</div>
          <div class="text-center text-sm text-[#888888]">工程地址：{{ pageQuery.calculate_name }}</div>
        </div>
        <div class="flex flex-col gap-3">
          <el-draggable-table
            @sort-data="handleSortData"
            :draggable-props="{
              handle: '.move',
            }"
            :data="finishedList"
            border
            id="myTable"
            header-align="center"
            :span-method="objectSpanMethod"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="序号" align="center" width="55" prop="drag" class-name="move" />
            <el-table-column prop="name" label="项目代号" align="center" width="180">
              <template #default="scope">
                {{ handleRoomName(scope.row.name, scope.row.house_number) }}
              </template>
            </el-table-column>
            <el-table-column prop="print_name" label="项目名称" align="center" width="180">
              <template #default="scope">
                <el-input
                  v-model="scope.row.print_name"
                  v-if="scope.row.name != '总计' && checkRule('预算明细修改权')"
                  :id="`nameInput${scope.row.id}`"
                  @input="handleBlueCompute(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" align="center" width="80">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit"
                  v-if="checkRule('预算明细修改权') && scope.row.name != '总计'"
                  @input="handleBlueCompute(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="number" label="数量" align="center" width="92">
              <template #default="scope">
                <el-input
                  v-model="scope.row.number"
                  v-if="checkRule('预算明细修改权') && scope.row.name != '总计'"
                  type="number"
                  @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="unit_price" label="单价" align="center" width="100">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit_price"
                  v-if="checkRule('预算明细修改权') && scope.row.name != '总计'"
                  type="number"
                  @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="total_price" label="合计" align="center" width="100" />
            <el-table-column label="备注" align="center">
              <template #default="scope">
                <el-input
                  v-if="checkRule('预算明细修改权') && scope.row.name != '总计'"
                  v-model="scope.row.remark"
                  type="textarea"
                  show-word-limit
                  :input-style="remarkStyle"
                  @change="handleBlueRemark(scope.row.remark)" />
              </template>
            </el-table-column>
          </el-draggable-table>
        </div>
      </div>
    </section>
    <el-dialog v-model="addDataDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="新增项目数据" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6" label-width="90">
          <el-form-item label="项目代号:" required>
            <el-input v-model="submitForm.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="项目名称:" required>
            <el-input v-model="submitForm.print_name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="房间层号:" required v-if="houseNumberOptions.length > 1">
            <el-select v-model="submitForm.house_number" placeholder="请选择">
              <el-option v-for="item in houseNumberOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="单位:" required>
            <el-input v-model="submitForm.unit" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="数量:" required>
            <el-input
              v-model="submitForm.value"
              placeholder="请输入"
              clearable
              type="number"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="单价:" required>
            <el-input
              v-model="submitForm.unit_price"
              placeholder="请输入"
              clearable
              type="number"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="合计:" required>
            <el-input v-model="total" placeholder="请输入" clearable disabled />
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <SelectExportMode
      :selectTemplateDialog="selectTemplateDialog"
      openCate="成品定制预算导出模板"
      @handleSaveMode="handleSaveMode"
      @handleCloseMode="handleCloseMode" />
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
  flex: 1;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
